package com.pms.api;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.rpc.SystemRpcService;
import com.pms.rpc.UserService;
import com.pms.service.*;
import com.pms.util.DateUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 二供模块 数据监测 接口 前端控制器
 * </p>
 *
 * @author asus
 * @since 2018-07-17
 */
@RestController
@RequestMapping("/iot/apiDataMonitoring")
@Api(value="二供模块 数据监测 Api接口" ,description = "二供模块 数据监测 Api接口")
public class ApiIotDataMonitoringController extends BaseController {
    @Autowired
    IIotAgencyService orgService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    @Autowired
    IIotWaterPumpGroupAttrService waterPumpGroupAttrService;
    @Autowired
    SystemRpcService systemRpcService;
    @Autowired
    IGroupIotAgencyService groupIotAgencyService;
    @Autowired
    IIotEqCameraService iotEqCameraService;
    @Autowired
    IIotRepairDeclareService iotRepairDeclareService;
    @Autowired
    IIotAlarmRecordService iotAlarmRecordService;
    @Autowired
    UserService userService;
    /*
    * 实时数据信息
    * @param
    * @return
    */
    @ApiOperation(value = "实时数据信息")
    @RequestMapping(value = "/realTimePage",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="水泵组id字符串(以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="communityId",value="小区id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="houseId",value="水泵房id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="searchValue",value="搜索框内容",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="deviceStatus",value="设备状态(0-在线,1-不在线)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="isResultDesc",value="是/否返回结果字段描述(1/2)",required = false,dataType = "int",paramType="form"),
    })
    public R realTimePage(String waterPumpGroupIds,Long communityId,Long houseId,String searchValue,Integer deviceStatus,Integer isResultDesc){
        // 获取当前用户角色
        Map<String,String> currentUserMap=getCurrentUserMap();
       Assert.parameterIsBlank(waterPumpGroupIds,"参数水泵组id不能为空");
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
       if (null==currentUserInfo||null==currentUserInfo.getId()){ return  R.error(400,"请重新登录");}
        Map<String,Object> userPermiss =userService.getApiPermission(Long.parseLong(currentUserInfo.getId()),2,"实时数据",1,null);
        if (null==userPermiss){
            return  R.error(400,"您没有进入该页面的权限");
        }
        List<Long> roleWaterPumpGroupIdList = null;
//        String roleWaterPumpGroupIds = null;
        if(1!=currentUserInfo.getGroupType()){// 自定义角色
            // 获取角色拥有的 机构id
            String roleAgencyIdsStr =groupIotAgencyService.getAgencyIdsStrByGroupId(currentUserInfo.getGroupId()+"");
            Assert.parameterIsBlank(roleAgencyIdsStr,"您暂无机构权限，请联系管理员");
//           roleWaterPumpGroupIds = waterPumpGroupService.getGroupIdsStrByHouseId(roleAgencyIdsStr);
            roleWaterPumpGroupIdList = waterPumpGroupService.getGroupIdListByHouseId(roleAgencyIdsStr);
            if(roleWaterPumpGroupIdList==null||roleWaterPumpGroupIdList.isEmpty()){// 未查询到 水泵组 直接返回空数据
                return R.ok().put("data",new ArrayList<>());
            }
        }
       if(!waterPumpGroupIds.equals("-1")){// 查询全部 - 系统级别
           List<Long> PumpGroupIdList = new ArrayList<Long>();
           StringTokenizer strTokenizer=new StringTokenizer(waterPumpGroupIds,",");
           try {
               while (strTokenizer.hasMoreElements()) {
                   PumpGroupIdList.add(Long.parseLong(strTokenizer.nextToken()));
               }
           }catch (NumberFormatException ex){
               return R.error(400,"参数水泵组id格式错误");
           }
           if(roleWaterPumpGroupIdList!=null){
               roleWaterPumpGroupIdList.retainAll(PumpGroupIdList);// 取交集
           }
           if(roleWaterPumpGroupIdList==null){
               roleWaterPumpGroupIdList=PumpGroupIdList;//直接赋值
           }
       }
        Wrapper<Map<String,Object>> wr = new EntityWrapper<Map<String,Object>>();
        wr.eq("wpGroup.company_code",currentUserMap.get("companyCode"));
        if(communityId!=null&&communityId.longValue()!=-1L){
            wr.eq("wpGroup.community_id",communityId);
        }
        if(houseId!=null&&houseId.longValue()!=-1L){
            wr.eq("wpGroup.house_id",houseId);
        }
        if(deviceStatus!=null){
            if(deviceStatus==0){
                wr.eq("wpGroupData.deviceStatus",deviceStatus);// 设备状态
            }// 默认查询全部
            if(deviceStatus==1){
                wr.andNew("wpGroupData.deviceStatus is null");// 设备状态
            }
        }
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("wpGroup.group_id", roleWaterPumpGroupIdList);
        }
        if(StringUtils.isNotBlank(searchValue)){// 搜索框内容 根据 水泵房名称和水泵名称 搜索
            wr.andNew("wpGroup.house_name like '%"+searchValue+"%' or wpGroup.group_name like '%"+searchValue+"%'");
        }
        List<Map<String,Object>> dataList = waterPumpGroupService.readRealTimeDataList(wr);
        List<Map<String,Object>> pumpAttrList = new ArrayList<Map<String,Object>>();
        int pumpGroupNum = dataList.size();

        // 如果是沃佳 点位
        List<Map<String,String>> tableList = new ArrayList<Map<String,String>>();
        Map<String,Integer> tableTagMap = new HashMap<String,Integer>();

        for(int x=pumpGroupNum-1,len=0;x>=len;x--){
            // 如果是沃佳数据
            Integer dataSources =(Integer) dataList.get(x).get("data_source");
            if(dataSources==null){dataSources = 1;}
            if(dataSources==2){
                String group_code = (String)dataList.get(x).get("group_code");
                String[] tableName = group_code.split("\\|");
                if(tableTagMap.get(tableName[0])==null){
                    tableTagMap.put(tableName[0],0);
                    Map<String,String> readSqlParam = new HashMap<String,String>();
                    readSqlParam.put("tableNameNum",tableName[0]);
                    readSqlParam.put("tableName","`"+tableName[0]+"`"); // 纯数字的表名需要转义
                    readSqlParam.put("column","*");
                    tableList.add(readSqlParam);
                }
            }
            if(dataSources==1) {
                Integer count = (Integer) dataList.get(x).get("count");// 小泵数量
                if (count == null) {// 无数据上报
                    count = 0;
                    dataList.get(x).put("count", 0);
                }
                if (count > 0) {
                    String[] SBZT_arr = dataList.get(x).get("SBZT").toString().split(",");
                    String[] waterFrequency_arr = dataList.get(x).get("waterFrequency").toString().split(",");
                    for (int y = 0; y < count; y++) {
                        Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
                        pumpAttrMap.put("pumpName", (y + 1) + "号泵");
                        // 水泵频率
                        pumpAttrMap.put("pumpFrequency", waterFrequency_arr.length > y ? waterFrequency_arr[y] : waterFrequency_arr[0]);
                        // 水泵运行状态
                        pumpAttrMap.put("pumpState", SBZT_arr.length > y ? SBZT_arr[y] : SBZT_arr[0]);
                        pumpAttrMap.put("pumpStateName", waterPumpGroupService.formatPumpStateStr(pumpAttrMap.get("pumpState") + ""));
                        pumpAttrMap.putAll(dataList.get(x));
                        pumpAttrList.add(pumpAttrMap);
                    }
                }
                if (count == 0) {
                    Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
                    pumpAttrMap.put("pumpName", "1号泵");
                    pumpAttrMap.putAll(dataList.get(x));
                    pumpAttrList.add(pumpAttrMap);
                }
                dataList.remove(x);
            }
        }

        // 解析 woGia 数据
        Map<String,Map<String,Object>> deviceAttrMap = waterPumpGroupService.getResolveWoGiaDataByTable(tableList);
        for(Map<String,Object> devMap :dataList){
           String group_code = (String)devMap.get("group_code");
            Map<String,Object> pumpAttrDetailMap = deviceAttrMap.get(group_code);
            if(pumpAttrDetailMap==null){
                Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
                pumpAttrMap.put("pumpName", "1号泵");
                pumpAttrMap.put("deviceStatus", 0);
                pumpAttrMap.putAll(devMap);
                pumpAttrList.add(pumpAttrMap);
                continue;
            }
            List<Map<String,Object>> pumpStateList = (List<Map<String,Object>>)pumpAttrDetailMap.get("pumpAttrList");
            if(pumpStateList==null||pumpStateList.isEmpty()){
                Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
                pumpAttrMap.put("pumpName", "1号泵");
                pumpAttrMap.put("deviceStatus", 0);
                pumpAttrMap.putAll(devMap);
                pumpAttrList.add(pumpAttrMap);
                continue;
            }
            for(Map<String,Object> pumpStateMap: pumpStateList){
                pumpStateMap.putAll(pumpAttrDetailMap);
                pumpStateMap.putAll(devMap);
                pumpStateMap.remove("pumpAttrList");
                pumpStateMap.put("deviceStatus", 0);
                pumpAttrList.add(pumpStateMap);
            }
        }
        if(isResultDesc!=null&&isResultDesc==1){
            return R.ok().put("data",pumpAttrList).put("pumpGroupNum",pumpGroupNum).put("pumpNum",pumpAttrList.size()).put("resultDesc",realTimePageResultDesc());
        }
        return R.ok().put("data",pumpAttrList).put("pumpGroupNum",pumpGroupNum).put("pumpNum",pumpAttrList.size());
    }

    /*
    * 电子地图设备信息
    * @param
    * @return
    */
    @ApiOperation(value = "电子地图信息")
    @RequestMapping(value = "/readWaterPumpMapInfo",method ={ RequestMethod.POST})
    @ApiImplicitParams({
        @ApiImplicitParam(name="level",value="地图展示级别(1-小区(默认),2-水泵房)",required = true,dataType = "int",paramType="form"),
        @ApiImplicitParam(name="communityId",value="小区id",required = false,dataType = "Long",paramType="form"),
        @ApiImplicitParam(name="houseId",value="水泵房id,不为空直接默认查询(2-水泵房)级别",required = false,dataType = "Long",paramType="form"),
        @ApiImplicitParam(name="isResultDesc",value="是/否返回结果字段描述(1/2)",required = false,dataType = "int",paramType="form"),
    })
    public R readWaterPumpMapInfo(Integer level,Long communityId,Long houseId,Integer isResultDesc){

        Assert.parameterIsNull(level,"参数level不能为空");
        if(level!=1&&level!=2){
            return R.error(400,"参数值level有误");
        }// 默认为小区 只有2级
        // 获取当前用户角色
        Map<String,String> currentUserMap=getCurrentUserMap();
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        if (null==currentUserInfo||null==currentUserInfo.getId()){ return  R.error(400,"请重新登录");}
        Map<String,Object> userPermiss =userService.getApiPermission(Long.parseLong(currentUserInfo.getId()),2,"电子地图",1,null);
        if (null==userPermiss){
            return  R.error(400,"您没有进入该页面的权限");
        }
        String roleAgencyIdsStr = null;
        if(1!=currentUserInfo.getGroupType()) {// 自定义角色
            // 获取角色拥有的 机构id
            roleAgencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId(currentUserInfo.getGroupId() + "");
            Assert.parameterIsBlank(roleAgencyIdsStr, "您暂无机构权限，请联系管理员");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("companyCode",currentUserMap.get("companyCode"));
        if(roleAgencyIdsStr!=null){
            paramMap.put("roleAgencyIdsStr",roleAgencyIdsStr);
        }
        if(communityId!=null&&communityId.longValue()!=-1L){
            paramMap.put("communityId",communityId);
        }
        if(houseId!=null&&houseId.longValue()!=-1L){
//            if(level!=2){
//                return R.error(400,"参数值level有误");
//            }
            paramMap.put("houseId",houseId);
        }
        paramMap.put("level",level);
        List<Map<String,Object>> agencyMapInfoList=orgService.selectAgencyMapInfoByLevel(paramMap);
        Map<String,Map<String,Object>> communityPumpNumMap = null;
        if(level == 1){
            communityPumpNumMap= waterPumpGroupService.getPumpNumByCommunityId(paramMap);
        }
        if(level != 1){
            communityPumpNumMap=  waterPumpGroupService.getPumpNumByHouseId(paramMap);
        }
        if(agencyMapInfoList==null){agencyMapInfoList = new ArrayList<Map<String,Object>>(); }
        for(int x=0,lenth=agencyMapInfoList.size();x<lenth;x++){
            Map<String,Object> pumpNumMap = communityPumpNumMap.get( agencyMapInfoList.get(x).get("id")+"" );
            if(pumpNumMap==null){
                pumpNumMap=new HashMap<String,Object>();
                if(level==1){
                    pumpNumMap.put("communityId", agencyMapInfoList.get(x).get("id"));
                }
                if(level != 1) {
                    pumpNumMap.put("houseId", agencyMapInfoList.get(x).get("id"));
                }
                pumpNumMap.put("onlinePumpNum",0);
                pumpNumMap.put("nolinePumpNum",0);
                pumpNumMap.put("totalPumpNum",0);
            }
            agencyMapInfoList.get(x).putAll(pumpNumMap);
            if(agencyMapInfoList.get(x).get("totalPumpNum")==null){
                agencyMapInfoList.get(x).put("totalPumpNum",0);
                agencyMapInfoList.get(x).put("onlinePumpNum",0);
                agencyMapInfoList.get(x).put("nolinePumpNum",0);
            }
            if(agencyMapInfoList.get(x).get("houseNum")==null){
                agencyMapInfoList.get(x).put("houseNum",0);
            }
            if(agencyMapInfoList.get(x).get("groupNum")==null){
                agencyMapInfoList.get(x).put("groupNum",0);
            }
        }
        if(isResultDesc!=null&&isResultDesc==1){
            return R.ok().put("data",agencyMapInfoList).put("resultDesc",readWaterPumpMapInfoResultDesc());
        }
        return R.ok().put("data",agencyMapInfoList);
    }

      /*
       * 水泵房设备组数据详情
       * @param
       * @return
       */
    @ApiOperation(value = "水泵房设备组数据详情")
    @RequestMapping(value = "/readPumpGroupInfoByHouse",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="level",value="级别level",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="isResultDesc",value="是/否返回结果字段描述(1/2)",required = false,dataType = "int",paramType="form"),
    })
    public R readWaterPumpGroupInfoByHouse(Long id, Integer level,Integer isResultDesc){
        Assert.parameterIsNull(id,"参数id不能为空");
        Assert.parameterIsNull(level,"参数level不能为空");
        Map<String,Object> paramMap = new HashMap<String,Object>();
        if(level==1){// 小区
            paramMap.put("communityId",id);
        }
        if(level!=1){// 水泵房
            paramMap.put("houseId",id);
        }
        List<Map<String,Object>> houseWaterPumpGroupList = waterPumpGroupService.readHousePumpGroupDetail(paramMap);
        if(houseWaterPumpGroupList==null){houseWaterPumpGroupList=new ArrayList<Map<String,Object>>();}
        List<Long> houseIdList = new ArrayList<Long>();
        List<Long> pumpGroupIdList = new ArrayList<Long>();
        for(int x=0,length=houseWaterPumpGroupList.size();x<length;x++){
            Long houseId = (Long) houseWaterPumpGroupList.get(x).get("houseId");
            Long pumpGroupId = (Long)houseWaterPumpGroupList.get(x).get("groupId");
            if(!houseIdList.contains(houseId )){
                houseIdList.add(houseId);
            }
            if(!pumpGroupIdList.contains(pumpGroupId )){
                pumpGroupIdList.add(pumpGroupId);
            }
        }
        Map<String,Object> cameraMap =null;
        if(level!=1) {
            cameraMap =iotEqCameraService.readHouseCamera(id);
        }
        if(cameraMap==null){
            cameraMap = new HashMap<String,Object>();
        }
        R  resultR = R.ok().put("data",houseWaterPumpGroupList).put("camera",cameraMap);
        resultR.put("houseNum",houseIdList.size());
        resultR.put("pumpGroupNum",pumpGroupIdList.size());
        resultR.put("pumpNum",houseWaterPumpGroupList.size());
        if(isResultDesc!=null&&isResultDesc==1){
            resultR.put("resultDesc",readWaterPumpGroupInfoByHouseResultDesc());
        }
        return resultR;
    }

    /*
       * 查询分区树结构
       * @param
       * @return
       */
    @ApiOperation(value = "选择设备组-查询机构树接口")
    @RequestMapping(value = "/readAgencyTreeByUser",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="readTreeLevel",value="查询树结构层级(1-系统,2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="checked",value="是否默认全部选中(0-未选中(默认),1-选中)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="opened",value="是否默认全部展开(0-未展开(默认),1-展开)",required = false,dataType = "int",paramType="form"),
    })
    public R readAgencyTreeByUser(Integer readTreeLevel,Integer checked,Integer opened){
        if(readTreeLevel==null||readTreeLevel<1){readTreeLevel = 5;}// 默认查询5级
        if(opened==null||opened!=1){opened=0;}
        if(checked==null||checked!=1){checked=0;}
        Map<String,Object> returnMap = new HashMap<String,Object>();
        returnMap.put("id",-1L);
        returnMap.put("name","系统");
        returnMap.put("code","system");
        returnMap.put("parentId",-2);
        returnMap.put("level",1);
        returnMap.put("checked",checked);
        returnMap.put("opened",opened);
        if(readTreeLevel==1){
            returnMap.put("children",new ArrayList< Map<String,Object>>());
            return R.ok().put("data",returnMap);
        }
        String agencyIdsStr = null;
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(roleType!=1) {
            agencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId( roleId+ "");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
        }
        Wrapper<IotAgency> agencyWp = new EntityWrapper<IotAgency>();
        agencyWp.eq("company_code",companyCode);
//        agencyWp.eq("status",1);
        if(agencyIdsStr!=null){
            agencyWp.in("agency_id",agencyIdsStr);
        }
        if(readTreeLevel<4){
            agencyWp.le("agency_level",readTreeLevel);//  判断 机构等级  <=
        }
        List<Map<String,Object>> treeList = orgService.selectMapList(agencyWp);
        if(readTreeLevel>4){//查询到水泵组
            Wrapper<IotWaterPumpGroup> waterPumpGroupWp = new EntityWrapper<IotWaterPumpGroup>();
            waterPumpGroupWp.eq("company_code",companyCode);
            if(agencyIdsStr!=null){
                waterPumpGroupWp.in("house_id",agencyIdsStr);
            }
            treeList.addAll( waterPumpGroupService.selectMapList(waterPumpGroupWp) );
        }
        List<Map<String,Object>> treeChildrenList = orgService.agencyFactorTree(treeList,checked,opened);
        returnMap.put("children",treeChildrenList);
        return R.ok().put("data",returnMap);
    }

    /*
      * 查询数据分析曲线
      * @param
      * @return
      */
    @ApiOperation(value = "查询数据分析曲线")
    @RequestMapping(value = "/readDataAnalysisCurve",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="monitorParam",value="监测参数(1-电流,2-电压,3-进水压力,4-出水压力,5-进水瞬时流量,6-出水瞬时流量)",required = true,dataType = "int",paramType="form"),
    })
    public R readWaterPumpGroupInfoByHouse(String waterPumpGroupIds,String startTime,String endTime,Integer monitorParam){
        Assert.parameterIsNull(waterPumpGroupIds,"参数waterPumpGroupIds不能为空");
        Assert.parameterIsBlank(startTime,"起始时间不能为空");
        Assert.parameterIsBlank(startTime,"截止时间不能为空");
        Assert.parameterIsNull(monitorParam,"请选择监控参数");
        String readColumn = getReadColumnName(monitorParam);
        Assert.parameterIsBlank(readColumn,"该监控参数暂无数据");
        Date startDate = DateUtil.stringToDate(startTime);
        if(startDate==null){
            return R.error(400,"起始时间格式有误");
        }
        Date endDate = DateUtil.stringToDate(endTime);
        if(endDate==null){
            return R.error(400,"截止时间格式有误");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("column",readColumn);
        paramMap.put("startTime",startDate);
        paramMap.put("endTime",endDate);
        if(waterPumpGroupIds!=null&&!waterPumpGroupIds.equals("-1")){
            paramMap.put("waterPumpGroupIds",waterPumpGroupIds);
        }
        paramMap.put("companyCode",getCurrentCompanyCode());
        List<Map<String,Object>> dataList = waterPumpGroupService.readDataAnalysisCurve(paramMap,null);
        if(dataList==null){dataList= new ArrayList<Map<String,Object>>();}
        for(int x=0,lenth=dataList.size();x<lenth;x++){
            List<String> retimeFormatList = (List<String>) dataList.get(x).get("timeArr");
            if(retimeFormatList==null||retimeFormatList.isEmpty()){
                dataList.get(x).put("valueArr",new ArrayList<>());
            }
        }
//        Map<String,Object> returnMap = new HashMap<String,Object>();
//        for(int x=0,length = dataList.size();x<length;x++){
//            returnMap.put(dataList.get(x).get("groupName").toString(),dataList.get(x));
//        }
        return R.ok().put("data",dataList);
    }

    /*
   * 查看机构信息集合
   * @param
   * @return
   */
    @ApiOperation(value = "查看机构信息列表")
    @RequestMapping(value = "/list",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="level",value="查询类型(2-物业/公司(默认),3-小区,4-水泵房,5-水泵组)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="parentId",value="上级id",required = false,dataType = "Long",paramType="form"),
    })
    public R list(Integer level,Long parentId){
        if(level==null||level<1||level>5){ level = 2;}// 默认查询  物业
        List<Map<String,Object>> returnList = null;
        // 获取当前用户角色
//        Map<String,String> currentUserMap=getCurrentUserMap();
//        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
//        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        // 获取当前角色 拥有的 机构id权限
        String agencyIdsStr = null;
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(1!=roleType){// 自定义角色
            agencyIdsStr =groupIotAgencyService.getAgencyIdsStrByGroupId(roleId+"");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
        }
        if(level==5){//查询水泵组
            Wrapper<IotWaterPumpGroup> WP = new EntityWrapper<IotWaterPumpGroup>();
            WP.eq("company_code",companyCode);
            if(null!=agencyIdsStr) {// 自定义角色 根据当前角色 拥有 权限 过滤
                WP.in("house_id", agencyIdsStr);
            }
            if(parentId!=null&& parentId.longValue()!=-1L){
                WP.eq("house_id",parentId);
            }
            returnList =waterPumpGroupService.selectMapList(WP);
        }
        if(level<5){// 查询 物业,小区,水泵房
            Wrapper<IotAgency> WP = new EntityWrapper<IotAgency>();
            WP.eq("company_code",companyCode);
            WP.eq("agency_level",level);
            if(null!=agencyIdsStr) {
                WP.in("agency_id", agencyIdsStr);//自定义角色 根据当前角色 拥有 权限 过滤
            }
            if(parentId!=null&&parentId.longValue()!=-1L){
                WP.eq("parent_id",parentId);
            }
            returnList =orgService.selectMapList(WP);
        }
        if(returnList==null){returnList=new ArrayList<Map<String,Object>>();}
        return R.ok().put("data",returnList);
    }
    private static String getReadColumnName(Integer monitorParam){
        if(monitorParam==null){return null;}
        switch (monitorParam){
            case 1: return null;// 电流
            case 2: return null;// 电压
            case 3: return "IFNULL(attr.SZGWYL,0.0) as value_";// 进水压力
            case 4: return "IFNULL(attr.pressureFeedback,0.0) as value_";// 出水压力
            case 5: return null;// 进水瞬时流量
            case 6: return null;// 出水瞬时流量
            default: return null;
        }
    }
    /**
     * 电子地图 小区水泵结果描述
     * @return
     */
    public static String readWaterPumpGroupInfoByHouseResultDesc(){
        return "gprsStatus-通讯状态，electricity -电流，voltage-电压,frequency-频率，entryCumulativeFlow-进水累计流量,exportCumulativeFlow-出水累计流量,exportInstantaneousFlow-出水瞬时流量,entryInstantaneousFlow-出水瞬时流量"
                        +"houseNum-水泵房数量,pumpGroupNum-水泵组数量,pumpNum-水泵数量,camera-摄像头参数对象"
        +"pumpName-水泵类型,reportTimeFormat-采集时间,devicestatus-设备状态(0-在线),pumpState-运行状态,pumpFrequency-频率"
        +" szgwyl-进水压力,pressureFeedback-出水压力,settingPressure-额定压力,houseName-水泵房名称,groupName-水泵组名称,communityName-小区名称";
    }

    /**
     * 电子地图信息 结果描述
     * @return
     */
    public static String readWaterPumpMapInfoResultDesc(){
        return "longitude-经度,latitude-纬度,id-id,level-级别,name-名称,parentName-上级名称,parentId-上级id,"
                +"groupNum-设备组数量,totalPumpNum-水泵数量,onlinePumpNum-在线水泵数量,nolinePumpNum-离线水泵数量,houseNum-水泵房数量";
    }
    /**
     * 实时数据 结果描述
     * @return
     */
    public static String realTimePageResultDesc(){
        return "gprsStatus-通讯状态，electricity -电流，voltage-电压,frequency-频率，entryCumulativeFlow-进水累计流量,exportCumulativeFlow-出水累计流量,exportInstantaneousFlow-出水瞬时流量,entryInstantaneousFlow-出水瞬时流量"
                +"community_name-所属小区,house_name-水泵房名,group_name-设备组名称,pumpName-水泵类型,deviceStatus-设备状态(0-在线),pumpState-运行状态,pumpStateName-运行状态,"
                +"pumpGroupNum-设备组数量,pumpNum-水泵数量,SZGWYL-进水压力,settingPressure-额定压力,pressureFeedback-出水压力";
    }

    /*
       * 查询数据分析曲线
       * @param
       * @return
       */
    @ApiOperation(value = "查询数据分析曲线-新接口(多组x轴对多组y轴)")
    @RequestMapping(value = "/readDataAnalysisCurve_new_xToy",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="monitorParam",value="监测参数(1-电流,2-电压,3-进水压力,4-出水压力,5-进水瞬时流量,6-出水瞬时流量)",required = true,dataType = "int",paramType="form"),
    })
    public R readDataAnalysisCurve_new_xToy(String waterPumpGroupIds,String startTime,String endTime,Integer monitorParam,Integer dataIsZero){
        Assert.parameterIsNull(waterPumpGroupIds,"参数waterPumpGroupIds不能为空");
        Assert.parameterIsBlank(startTime,"起始时间不能为空");
        Assert.parameterIsBlank(startTime,"截止时间不能为空");
        Assert.parameterIsNull(monitorParam,"请选择监控参数");
        String readColumn = getReadColumnName(monitorParam);
        Assert.parameterIsBlank(readColumn,"该监控参数暂无数据");
        Date startDate = DateUtil.stringToDate(startTime);
        if(startDate==null){
            return R.error(400,"起始时间格式有误");
        }
        Date endDate = DateUtil.stringToDate(endTime);
        if(endDate==null){
            return R.error(400,"截止时间格式有误");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("column",readColumn);
        paramMap.put("startTime",startDate);
        paramMap.put("endTime",endDate);
        if(waterPumpGroupIds!=null&&!waterPumpGroupIds.equals("-1")){
            paramMap.put("waterPumpGroupIds",waterPumpGroupIds);
        }
        paramMap.put("companyCode",getCurrentCompanyCode());
        List<Map<String,Object>>  dataList = waterPumpGroupService.readDataAnalysisCurve(paramMap,2);
        return R.ok().put("data",dataList);
    }


    @ApiOperation(value = "监控首页 设备在线离线个数")
    @RequestMapping(value = "/readWaterPumpStatusCount",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="isResultDesc",value="是/否返回结果字段描述(1/2)",required = false,dataType = "int",paramType="form"),
    })
    public R readWaterPumpStatusCount(Integer isResultDesc){
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        String agencyIdsStr = null;// 角色 权限内 水泵房id字符串
        List<Long> roleWaterPumpGroupIdList = null;// 角色 权限内 水泵组id集合
        Integer totalPumpNum = 0;
        Integer onLinePumpNum = 0;
        Map<String,Object> resultMap = new HashMap<String,Object>();
       R resultR = R.ok();
       if(isResultDesc!=null&&isResultDesc==1){
           resultR.put("desc",readWaterPumpStatus());
       }
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(roleType!=1) {// 自定义角色
            agencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId( roleId+ "");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
            roleWaterPumpGroupIdList = waterPumpGroupService.getGroupIdListByHouseId(agencyIdsStr);
            if(roleWaterPumpGroupIdList==null||roleWaterPumpGroupIdList.isEmpty()){// 未查询到 水泵组 直接返回空数据
                resultMap.put("onLine",0);
                resultMap.put("offLine",0);
                resultMap.put("repairStatus",0);
                resultMap.put("alarmStatus",0);
                return resultR.put("data",resultMap);
            }
        }
        Wrapper<Map<String,Object>> wr = new EntityWrapper<Map<String,Object>>();
        wr.eq("wpGroup.company_code",companyCode);
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("wpGroup.group_id", roleWaterPumpGroupIdList);
        }
        totalPumpNum = waterPumpGroupService.selectWaterPumpStatusCount(wr);
        wr.eq("wpGroupData.deviceStatus",0);// 设备状态
        onLinePumpNum = waterPumpGroupService.selectWaterPumpStatusCount(wr);
        resultMap.put("onLine",onLinePumpNum);
        resultMap.put("offLine",totalPumpNum - onLinePumpNum);

        // 查询 角色 报修未读记录
        Wrapper<IotRepairDeclare> repairDeclareWp = new EntityWrapper<IotRepairDeclare>();
        repairDeclareWp.eq("company_code",companyCode);
//        repairDeclareWp.eq("role_id",roleId);
        repairDeclareWp.eq("is_read",2);// 查询未读
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            repairDeclareWp.in("group_id", roleWaterPumpGroupIdList);
        }
        Integer noReadRepairNum =iotRepairDeclareService.selectCount(repairDeclareWp);
        if(noReadRepairNum>0){
            resultMap.put("repairStatus",1);
        }else{
            resultMap.put("repairStatus",0);
        }
        resultMap.put("noReadRepairNum",noReadRepairNum);
        // 查询 角色 报警 未读记录
        EntityWrapper<Map<String, Object>> alarmRecordWp = new EntityWrapper<Map<String, Object>>();
        alarmRecordWp.eq("wpg.company_code",companyCode);
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            alarmRecordWp.in("wpg.group_id", roleWaterPumpGroupIdList);
        }
        alarmRecordWp.eq("ar.is_reade",2);
        Integer noReadAlarmRecordNum =iotAlarmRecordService.selectNoReadAlarmRecordCount(alarmRecordWp);
        if(noReadAlarmRecordNum>0){
            resultMap.put("alarmStatus",1);
        }else{
            resultMap.put("alarmStatus",0);
        }
        resultMap.put("noReadAlarmRecordNum",noReadAlarmRecordNum);
        return resultR.put("data",resultMap);
    }

    /**
     * 监控首页 设备在线离线个数 结果描述
     * @return
     */
    public static String readWaterPumpStatus(){
        return "repairStatus-报修状态(0-无未读消息,1-有未读消息)，alarmStatus -报警状态(1/0-有/无未读消息),onLine-在线设备组数量，offLine-离线设备组数量"
                +"noReadAlarmRecordNum-未阅读的报警记录数量，noReadRepairNum-未阅读的报修记录数量";
    }
}
